<?php
class ModelToolOtherOrders extends Model {
    public function addNew($fileUnique, $uploadType) {
        $sql = "INSERT INTO `excel_upload_log` SET `user_id`='".$this->user->getId()."',`file_unique`='".$this->db->escape($fileUnique)."',`upload_type`='".$this->db->escape($uploadType)."',`date_added`='".date('Y-m-d H:i:s')."'";
        $this->db->query($sql);
        return $this->db->getLastId();
    }

    public function importFailed($pk) {
        $sql = "UPDATE `excel_upload_log` SET `status`='0' WHERE `excel_upload_log_id`='".$pk."'";
        $this->db->query($sql);
    }

       	public function getpro($product_code) {
        $sql = "SELECT product_group.child_product_code,product_group.child_product_id,product_group.child_quantity  FROM product_group WHERE product_group.parent_product_code=".$product_code."0";
        $query = $this->db->query($sql);
     	$data = $query->rows;
     	return $data;
    }

    

    public function getProvendor($product_datas,$time) {
    	// $sql = "SELECT v.vproduct_id, vs.user_id, vs.vendor_name, v.product_cost, p.product_id, pv.product_code, p.sku, p.packing_no, pd.`name` AS pname, od.option_id, od.`name` AS oname FROM vendor AS v LEFT JOIN vendors AS vs ON v.vendor = vs.vendor_id LEFT JOIN product AS p ON v.vproduct_id = p.product_id LEFT JOIN product_option_value AS pv ON pv.product_id = p.product_id LEFT JOIN product_description AS pd ON p.product_id = pd.product_id LEFT JOIN option_value_description AS od ON pv.option_value_id = od.option_value_id GROUP BY p.product_code"; 
    	// $query = $this->db->query($sql);
     // 	$data = $query->rows;
     // 	foreach ($data as $key => $value) {
     //        	$value['product_code'] = substr($value['product_code'], 0, 10);
     //        	// var_dump($value['product_code']);

     // 			if (!empty($value['product_code'])&&($value['product_code'] == $product_datas[$value['product_code']]['product_code'])) {
     //        		// echo '@';
     //        		// echo "qq".$value['product_code'];

     // 				$value['qty'] = $product_datas[$value['product_code']]['qty'];
     // 				// var_dump($arr[$value['user_id']]);
     // 				// var_dump($value);
     // 				$arr[$value['user_id']][] = $value;
     				
     // 			}
     // 	}

    	foreach ($product_datas as $key => $value) {
    		$sql = "SELECT v.vproduct_id, vs.user_id, vs.vendor_name, v.product_cost, p.product_id, pv.product_code, p.sku, p.packing_no, pd.`name` AS pname, od.option_id, od.`name` AS oname FROM vendor AS v LEFT JOIN vendors AS vs ON v.vendor = vs.vendor_id LEFT JOIN product AS p ON v.vproduct_id = p.product_id LEFT JOIN product_option_value AS pv ON pv.product_id = p.product_id LEFT JOIN product_description AS pd ON p.product_id = pd.product_id LEFT JOIN option_value_description AS od ON pv.option_value_id = od.option_value_id where p.product_code =".$value['product_code']; 
    		// var_dump($value);
    		// echo $sql;die();
	    	$query = $this->db->query($sql);
	     	// $data = $query->row;
	     	$datatime= $value['time'].','.$query->row['user_id'];
	     	$data['qty'] = $value['qty'];
	     	$data['vproduct_id'] = $query->row['vproduct_id'];
	     	$data['user_id'] = $query->row['user_id'];
	     	$data['vendor_name'] = $query->row['vendor_name'];
	     	$data['product_cost'] = $query->row['product_cost'];
	     	$data['product_id'] = $query->row['product_id'];
	     	$data['product_code'] = $query->row['product_code'];
	     	$data['sku'] = $query->row['sku'];
	     	$data['packing_no'] = $query->row['packing_no'];
	     	$data['pname'] = $query->row['pname'];
	     	$data['oname'] = $query->row['oname'];

	     	$arr[$datatime][] = $data;
	     	
    	}
    	// var_dump($arr);die();
     	foreach ($arr as $key => $value) {
     		$karr = explode(',',$key );
     		// var_dump($karr);die();
   
     		$pdata = array(
     			'user_id' => 81,
		        'date_added'=>date('Y-m-d H:i:s'),
     			'status' =>0 ,
     			'vendor_id' =>$karr[1] ,
     			'warehouse_id' =>4,
     			 );
			$po_id = M('po')->add($pdata);
			$sdata = array(
     			'user_id' => 81,
     			'refer_id' => $po_id,
     			'refer_type_id' => 2,
		        'date_added'=>date('Y-m-d H:i:s'),
     			'status' =>0 ,
     			'comment' =>'excel导入',
     			'warehouse_id' =>4,
     			 );
			// $in_id = M('stock_in')->add($sdata);
			$price=0;
     		foreach ($value as $key1 => $value1) {
     			if (empty($value1['product_code'])) {
     				continue;
     			}
     			// var_dump($value1);die();
     			$product_data['po_id'] = $po_id;
				$product_data['product_id'] = $value1['product_id'];
				$product_data['qty'] = $value1['qty'];
				$product_data['delivered_qty'] = 0;
				$product_data['unit_price'] = $value1['product_cost'];
				$product_data['price'] = $product_datas['qty']* $product_datas['product_cost'];
				$product_data['status'] = 6;
				$product_data['name'] = $value1['pname'];
				$product_data['product_code'] = $value1['product_code'];
				$product_data['sku'] = $value1['sku'];
				$product_data['comment'] = $value1['comment'];
				$product_data['sort_order'] = 0;
				$product_data['option_id'] = $value1['option_id'];
				$product_data['option_name'] = $value1['oname'];
				$product_data['packing_no'] = $value1['packing_no'];
				M('po_product')->add($product_data);
				$price +=$product_data['qty']* $product_data['unit_price'];
				$stdata = array(
					'product_code' => $value1['product_code'],
					'in_id' => $in_id,
					'product_quantity' => $value1['qty'] ,
					'product_price' => $value1['product_cost'],
					'products_money' => $value1['qty']* $value1['product_cost'],
					'date_added' => date('Y-m-d H:i:s'),
				 );
				// var_dump($stdata);
				// M('stock_in_detail')->add($stdata);
				// echo M('stock_in_detail')->getLastsql();die();

			}
			M('po')->data(array('total'=>$price,'date_modified'=>date('Y-m-d H:i:s')))->where(array('id'=>$po_id))->save();	
			// M('stock_in')->data(array('buy_money'=>$price))->where(array('in_id'=>$in_id))->save();	
			$shdata = array(
				'in_id' => $in_id, 
     			'user_id' => 160,
				'operator_name' =>'永康物流营销部', 
				'comment' =>'excel导入',
				'date_added' => date('Y-m-d H:i:s'), 
			);
			// M('stock_in_history')->add($shdata);
			$shdata = array(
				'po_id' => $po_id, 
     			'user_id' => 160,
				'operator_name' =>'永康物流营销部', 
				'comment' =>'excel导入', 
				'date_added' => date('Y-m-d H:i:s'),
			);
			M('po_history')->add($shdata);
     		$this->addInven(10,$value,2,$in_id,date('Y-m-d H:i:s'));
     	}
    }


        //入库单完成时，修改后台库存
	public function addInven($warehouse_id,$data,$refer_type_id, $in_id=0,$time){
		// var_dump($data);
		foreach ($data as $key => $value) {
			$value['product_code'] = $value['product_code'];
			$productNum = M('inventory')
			->field('id,available_quantity,product_code,account_quantity,qty_in_onway')
			->where(array('product_code' => $value['product_code'],'warehouse_id'=>$warehouse_id))
			->find();
			if (empty($productNum)) {
				$data = array(
					'warehouse_id'=>$warehouse_id, 
		  			'product_code'=>$value['product_code'],
		  		 	'available_quantity'=>$value['qty'], 
		  		 	'account_quantity'=>$value['qty'], 
					'date_added'=>$time);
			  	$inventoryPK = M('inventory')->data($data)->add();
			}else{
				$total=(int)$productNum['available_quantity']+(int)$value['qty'];
				$totalc=(int)$productNum['account_quantity']+(int)$value['qty'];
				M('inventory')-> where(array('product_code' => $value['product_code'],'warehouse_id'=>$warehouse_id))->data(array('available_quantity'=>$total,'account_quantity'=>$totalc,'date_modified'=>date('Y-m-d H:i:s')))->save();
				if ($refer_type_id==2) {
					$totalo=max(0, (int)$productNum['qty_in_onway']-(int)$value['qty']);
					M('inventory')-> where(array('product_code' => $value['product_code'],'warehouse_id'=>$warehouse_id))->data(array('qty_in_onway'=>$totalo,'date_modified'=>date('Y-m-d H:i:s')))->save();
				}
                $inventoryPK = $productNum['id'];
			}

            /*
             * 入库单修改库存后保存库存变更日志
             * @author sonicsjh
             */
            if (0 != (int)$value['qty']){
                $inventoryHistoryData = array(
                    'inventory_id'  => $inventoryPK,//inventory表PK
                    'product_code'  => $value['product_code'],//商品编码（冗余字段）
                    'warehouse_id'  => $warehouse_id,//仓库编号（冗余字段）
                    'account_qty'   => (int)$value['qty'],//财务数量变更（正+ 负-）
                    'available_qty' => (int)$value['qty'],//可用数量变更（正+ 负-）
                    'comment'       => '入库单：'.$in_id.' 完成入库。',//备注（入库单完成、损益单完成、出库单生成、出库单修改、出库单作废）
                    'user_id'       => 160,//操作人PK
                    'date_added'    => $time,//条目创建时间
                );
                M('inventory_history')->data($inventoryHistoryData)->add();
            }

			// $this->addInventoryfront($value['product_code'],$value['qty']);
		}
	}
}
